package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.ClassConvertUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyWeiJieHua;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeWeiJieHua;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 *  微借花
 *
 *  api买量对接 链接: https://apifox.com/apidoc/shared-364f5083-947a-4aab-b16c-d29bc9840558  访问密码: dYz8y5y1
 *
 *  @author WJB
 */
@ApiPlan(productId = "5", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatWeiJieHuaPhoneMd5Convert implements ApiPlatformPhoneMd5ConvertHandler {

    private static final String KEY = "P5mXH90POiDQxG09";
    private static final String CHANNEL_ID = "245";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {
        ApiPlatDataExchangeWeiJieHua data = new ApiPlatDataExchangeWeiJieHua();
        data.setPhoneMd5(apiDataExchangeParameter.getPhoneMd5());
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getUserName())) {
            data.setNameMd5(MD5.create().digestToHex(apiDataExchangeParameter.getUserName()));
        }

        //  年龄
        data.setAge(ClassConvertUtils.toInt(apiDataExchangeParameter.getAge()));
        //  性别 1男 2女
        Integer sex = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "1", 2)
                .when(apiDataExchangeParameter.getSex(), "0", 1)
                .end(1);
        data.setSex(sex);
        //  城市名称
        data.setCity(apiDataExchangeParameter.getCity());
        //  信用情况
        String overdue = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", "0")
                .when(apiDataExchangeParameter.getOverdue(), "2", "1")
                .when(apiDataExchangeParameter.getOverdue(), "3", "1")
                .end("1");
        data.setXinyong(overdue);
        //  职业
        String career = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", "2")
                .when(apiDataExchangeParameter.getCareer(), "2", "3")
                .when(apiDataExchangeParameter.getCareer(), "3", "0")
                .when(apiDataExchangeParameter.getCareer(), "4", "1")
                .when(apiDataExchangeParameter.getCareer(), "5", "3")
                .end("3");
        data.setOccupation(career);
        //  芝麻分
        String zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", "4")
                .when(apiDataExchangeParameter.getSesameCredit(), "2", "3")
                .when(apiDataExchangeParameter.getSesameCredit(), "3", "2")
                .when(apiDataExchangeParameter.getSesameCredit(), "4", "1")
                .end("0");
        data.setZhima(zhima);
        //  公积金
        String providentFund = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", "0")
                .when(apiDataExchangeParameter.getProvidentFund(), "2", "3")
                .when(apiDataExchangeParameter.getProvidentFund(), "3", "2")
                .when(apiDataExchangeParameter.getProvidentFund(), "4", "3")
                .end("0");
        data.setGjj(providentFund);
        //  社保
        String socialSecurity = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", "0")
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", "3")
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", "2")
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", "3")
                .end("0");
        data.setShebao(socialSecurity);
        //  车产
        String vehicle = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", "0")
                .when(apiDataExchangeParameter.getCarInfo(), "2", "1")
                .when(apiDataExchangeParameter.getCarInfo(), "3", "1")
                .when(apiDataExchangeParameter.getCarInfo(), "4", "1")
                .end("0");
        data.setCar(vehicle);
        //  房产
        String house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", "0")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", "1")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", "1")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", "1")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", "1")
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", "1")
                .end("0");
        data.setHouse(house);
        //  商业保险
        String commericalInsurance = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", "0")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", "3")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", "1")
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", "3")
                .end("0");
        data.setBaodan(commericalInsurance);
        //  信用卡
        String creditCard = ChooseEq.create()
                .when(apiDataExchangeParameter.getCreditLimit(), "1", "0")
                .when(apiDataExchangeParameter.getCreditLimit(), "2", "1")
                .when(apiDataExchangeParameter.getCreditLimit(), "3", "1")
                .when(apiDataExchangeParameter.getCreditLimit(), "4", "1")
                .when(apiDataExchangeParameter.getCreditLimit(), "5", "1")
                .when(apiDataExchangeParameter.getCreditLimit(), "6", "1")
                .end("0");
        data.setCreditCard(creditCard);
        //  代发
        String salaryPayMethod = ChooseEq.create()
                .when(apiDataExchangeParameter.getSalaryPayMethod(), "1", "1")
                .when(apiDataExchangeParameter.getSalaryPayMethod(), "2", "2")
                .when(apiDataExchangeParameter.getSalaryPayMethod(), "3", "3")
                .end();
        data.setSalaryType(salaryPayMethod);
        //  月收入
        String monthlySalary = ChooseEq.create()
                .when(apiDataExchangeParameter.getMonthlySalary(), "1", "1")
                .when(apiDataExchangeParameter.getMonthlySalary(), "2", "1")
                .when(apiDataExchangeParameter.getMonthlySalary(), "3", "2")
                .when(apiDataExchangeParameter.getMonthlySalary(), "4", "2")
                .when(apiDataExchangeParameter.getMonthlySalary(), "5", "2")
                .end("1");
        data.setMonthIncome(monthlySalary);
        //  ip
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getIp())) {
            data.setIp(apiDataExchangeParameter.getIp());
        } else {
            data.setIp("127.0.0.1");
        }

        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("orgId", CHANNEL_ID);
            newMap.put("data", dataStr);
        });
        return JsonUtils.toJson(map);
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) {
        ApiPlatApplyWeiJieHua data = new ApiPlatApplyWeiJieHua();
        data.setOrderId(apiApplyParameter.dataExchangeApplyId());
        data.setPhone(apiApplyParameter.getPhone());
        data.setName(apiApplyParameter.getUserName());
        //  年龄
        data.setAge(ClassConvertUtils.toInt(apiApplyParameter.getAge()));
        //  性别 1男 2女
        Integer sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "1", 2)
                .when(apiApplyParameter.getSex(), "0", 1)
                .end(1);
        data.setSex(sex);
        //  城市名称
        data.setCity(apiApplyParameter.getCity());
        //  信用情况
        String overdue = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", "0")
                .when(apiApplyParameter.getOverdue(), "2", "1")
                .when(apiApplyParameter.getOverdue(), "3", "1")
                .end("1");
        data.setXinyong(overdue);
        //  职业
        String career = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", "2")
                .when(apiApplyParameter.getCareer(), "2", "3")
                .when(apiApplyParameter.getCareer(), "3", "0")
                .when(apiApplyParameter.getCareer(), "4", "1")
                .when(apiApplyParameter.getCareer(), "5", "3")
                .end("1");
        data.setOccupation(career);
        //  芝麻分
        String zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", "4")
                .when(apiApplyParameter.getSesameCredit(), "2", "3")
                .when(apiApplyParameter.getSesameCredit(), "3", "2")
                .when(apiApplyParameter.getSesameCredit(), "4", "1")
                .end("0");
        data.setZhima(zhima);
        //  公积金
        String providentFund = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", "0")
                .when(apiApplyParameter.getProvidentFund(), "2", "3")
                .when(apiApplyParameter.getProvidentFund(), "3", "2")
                .when(apiApplyParameter.getProvidentFund(), "4", "3")
                .end("0");
        data.setGjj(providentFund);
        //  社保
        String socialSecurity = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", "0")
                .when(apiApplyParameter.getSocialSecurity(), "2", "3")
                .when(apiApplyParameter.getSocialSecurity(), "3", "2")
                .when(apiApplyParameter.getSocialSecurity(), "4", "3")
                .end("0");
        data.setShebao(socialSecurity);
        //  车产
        String vehicle = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", "0")
                .when(apiApplyParameter.getCarInfo(), "2", "1")
                .when(apiApplyParameter.getCarInfo(), "3", "1")
                .when(apiApplyParameter.getCarInfo(), "4", "1")
                .end("0");
        data.setCar(vehicle);
        //  房产
        String house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", "0")
                .when(apiApplyParameter.getRealEstateInfo(), "2", "1")
                .when(apiApplyParameter.getRealEstateInfo(), "3", "1")
                .when(apiApplyParameter.getRealEstateInfo(), "4", "1")
                .when(apiApplyParameter.getRealEstateInfo(), "5", "1")
                .when(apiApplyParameter.getRealEstateInfo(), "6", "1")
                .end("0");
        data.setHouse(house);
        //  商业保险
        String commericalInsurance = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", "0")
                .when(apiApplyParameter.getInsurancePolicy(), "2", "3")
                .when(apiApplyParameter.getInsurancePolicy(), "3", "1")
                .when(apiApplyParameter.getInsurancePolicy(), "4", "3")
                .end("0");
        data.setBaodan(commericalInsurance);
        //  信用卡
        String creditCard = ChooseEq.create()
                .when(apiApplyParameter.getCreditLimit(), "1", "0")
                .when(apiApplyParameter.getCreditLimit(), "2", "1")
                .when(apiApplyParameter.getCreditLimit(), "3", "1")
                .when(apiApplyParameter.getCreditLimit(), "4", "1")
                .when(apiApplyParameter.getCreditLimit(), "5", "1")
                .when(apiApplyParameter.getCreditLimit(), "6", "1")
                .end("0");
        data.setCreditCard(creditCard);
        //  代发
        String salaryPayMethod = ChooseEq.create()
                .when(apiApplyParameter.getSalaryPayMethod(), "1", "1")
                .when(apiApplyParameter.getSalaryPayMethod(), "2", "2")
                .when(apiApplyParameter.getSalaryPayMethod(), "3", "3")
                .end();
        data.setSalaryType(salaryPayMethod);
        //  月收入
        String monthlySalary = ChooseEq.create()
                .when(apiApplyParameter.getMonthlySalary(), "1", "1")
                .when(apiApplyParameter.getMonthlySalary(), "2", "1")
                .when(apiApplyParameter.getMonthlySalary(), "3", "2")
                .when(apiApplyParameter.getMonthlySalary(), "4", "2")
                .when(apiApplyParameter.getMonthlySalary(), "5", "2")
                .end("1");
        data.setMonthIncome(monthlySalary);
        //  ip
        if (ValidParam.isNotEmpty(apiApplyParameter.getIp())) {
            data.setIp(apiApplyParameter.getIp());
        } else {
            data.setIp("127.0.0.1");
        }

        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("orgId", CHANNEL_ID);
            newMap.put("data", dataStr);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if(!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONObject resData = JsonUtils.get(respJson).getJSONObject("data");
        JSONArray resProtocolList = resData.getJSONArray("protocolList");

        String orderId = resData.getString("orderId");
        String url = resData.getString("url");
        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("productOrgName");
        String productName = resData.getString("productName");
        String logo = resData.getString("logoUrl");
        List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
            if (ValidParam.isNotEmpty(resProtocolList)) {
                for (int i = 0; i < resProtocolList.size(); i++) {
                    JSONObject protocolObject = resProtocolList.getJSONObject(i);
                    ApiProtocol protocol = new ApiProtocol();
                    protocol.setProtocolName(protocolObject.getString("protocolName"));
                    protocol.setProtocolUrl(protocolObject.getString("protocolUrl"));
                    newList.add(protocol);
                }
            }
        });

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();


        result.setPrice(price);
        result.setLogoPath(logo);
        result.setApplyId(orderId);
        result.setCallUrl(url);
        result.setDisplayName(companyName);
        result.setProductName(productName);
        result.setProtocolList(protocolList);
        return result;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        JSONObject jsonObject = JsonUtils.get(requestVO.getBody());
        String orgId = jsonObject.getString("data");

        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.decryptFromBase64Str(orgId);

        RespPlatformNoticeApply applyNotice = new RespPlatformNoticeApply();
        applyNotice.setApplyId(dataStr);
        return applyNotice;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        boolean b = apiBizStatus.hasBizSuc();

        if (b) {
            return MapUtils.newHashMap(newHashMap -> {
                newHashMap.put("code", 200);
                newHashMap.put("msg", "操作成功");
            });
        }
        return MapUtils.newHashMap(newHashMap -> {
            newHashMap.put("code", 500);
            newHashMap.put("msg", "操作失败");
        });
    }
}
